<template>
  <div>
    <el-card class="box-card" style="margin:20px">
      <div slot="header" class="clearfix">
        <el-form :inline="true">
          <el-form-item v-if="routeData.itemId != null" style="margin-bottom:0px;">
            <el-button icon="el-icon-back" @click="back">返回</el-button>
          </el-form-item>
          <el-form-item label="名称" style="margin-bottom:0px;">
            <el-input v-model="searchName" placeholder="输入名称" />
          </el-form-item>
          <el-form-item label="模板编码" style="margin-bottom:0px;">
            <el-input v-model="formData.code" placeholder="输入模板编码" />
          </el-form-item>
          <!-- <el-form-item label="业务系统" style="margin-bottom:0px;">
            <el-select
              v-model="formData.systemId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in systemOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item style="margin-bottom:0px;">
            <el-button type="primary" icon="el-icon-search" @click="getFormList">查询</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="add">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData" :row-class-name="tableRowClassName" style="width: 100%">
        <el-table-column
          prop="name"
          label="名称"
          min-width="40%"
        />
        <el-table-column
          prop="code"
          label="模板编码"
          min-width="30%"
        />
        <el-table-column
          prop="systemName"
          label="业务系统"
          min-width="30%"
        />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="25%"
        />
        <el-table-column
          prop="version"
          label="版本号"
          min-width="10%"
        />
        <!-- <el-table-column
          prop="active"
          label="状态"
          min-width="13%"
          :formatter="formatActive"
        /> -->
        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              v-if="routeData.itemId != null"
              size="mini"
              type="success"
              icon="el-icon-paperclip"
              @click="bind(scope.$index, scope.row)"
            >
              绑定
            </el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="update(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="info"
              icon="el-icon-document"
              @click="edit(scope.$index, scope.row)"
            >
              模板
            </el-button>
            <el-button
              v-if="routeData.itemId == null"
              size="mini"
              type="success"
              icon="el-icon-document"
              @click="version(scope.$index, scope.row)"
            >
              版本
            </el-button>
            <el-popconfirm
              v-if="routeData.itemId == null"
              style="margin-left:10px;margin-right:10px"
              title="确定要复制这个模板吗？"
              @confirm="copy(scope.$index, scope.row)"
            >
              <el-button
                slot="reference"
                size="mini"
                type="primary"
                icon="el-icon-document"
              >
                复制
              </el-button>
            </el-popconfirm>
            <el-button
              v-if="routeData.itemId == null"
              size="mini"
              type="danger"
              icon="el-icon-document"
              @click="remove(scope.$index, scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float:right;margin:20px">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div>
        <el-dialog title="模板信息" :visible.sync="dialogFormVisible">
          <el-form ref="templateForm" label-width="100px" size="mini" :model="templateForm" :rules="rules">
            <el-form-item label="模板名称" prop="templateName">
              <el-input
                v-model="templateForm.templateName"
              />
            </el-form-item>
            <!-- <el-form-item label="模板编码" prop="templateCode">
              <el-input
                v-model="templateForm.templateCode"
              />
            </el-form-item> -->
            <el-form-item label="所属系统" prop="systemId">
              <el-select
                v-model="templateForm.systemId"
                placeholder="请选择"
                style="width: 100%"
                :disabled="updateTemplateId !== 0"
              >
                <el-option
                  v-for="item in systemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="状态" prop="active">
              <el-radio-group v-model="templateForm.active">
                <el-radio :label="0">不可用</el-radio>
                <el-radio :label="1">可用</el-radio>
              </el-radio-group>
            </el-form-item> -->
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 其它版本模板列表 -->
        <el-dialog title="模板" :visible.sync="dialogVersionVisible">
          <div>
            <el-table height="380" :data="versionData" style="width: 100%">
              <el-table-column
                prop="name"
                label="名称"
                min-width="40%"
              />
              <el-table-column
                prop="updateTime"
                label="更新时间"
                min-width="60%"
              />
              <el-table-column
                prop="version"
                label="版本号"
                min-width="25%"
              />
              <el-table-column
                align="center"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="success"
                    @click="use(scope.$index, scope.row)"
                  >
                    启用
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-pagination
              :current-page="versionCurrentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="versionPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="versionTotal"
              @size-change="versionHandleSizeChange"
              @current-change="versionHandleCurrentChange"
            />
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      routeData: this.$route.params,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      templateForm: {
        templateName: '',
        // templateCode: '',
        // active: 0,
        systemId: ''
      },
      rules: {
        templateName: [
          { required: true, message: '请输入表单名称', trigger: 'blur' }
        ],
        // templateCode: [
        //   { required: true, message: '请输入表单编码', trigger: 'blur' }
        // ],
        systemId: [
          { required: true, message: '请选择业务系统', trigger: 'change' }
        ]
      },
      updateTemplateId: 0,
      systemOptions: [],
      searchName: '',
      dialogVersionVisible: false,
      versionData: [],
      versionCurrentPage: 1,
      versionPageSize: 10,
      versionTotal: 0,
      useId: 0,
      loading: false,
      formConfig: '',
      formData: {
        code: null,
        systemId: null
      }
    }
  },
  created() {
    if (this.routeData.currentPage != null && this.routeData.pageSize != null) {
      this.currentPage = this.routeData.currentPage
      this.pageSize = this.routeData.pageSize
    }
  },
  mounted() {
    this.getFormList()
    this.getSystemOptions()
  },
  methods: {
    getFormList: function() {
      this.loading = true
      var params = {
        'pageSize': this.pageSize,
        'pageNum': this.currentPage,
        'name': this.searchName,
        'code': this.formData.code,
        'systemId': this.formData.systemId
      }
      this.$axios.get(this.baseFormUrl + '/template/page', {
        params
      }).then(res => {
        this.tableData = res.data.data.records
        this.total = parseInt(res.data.data.total)
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取模板列表失败')
      })
    },
    edit: function(index, row) {
      var params = {
        'id': row.id,
        'name': row.name,
        'content': row.content,
        'systemId': row.systemId
      }
      localStorage.setItem('currentFormTemplate', params.content ? params.content : '')
      this.setRouterParams(params)
      debugger
      this.$router.push({ name: 'templateFrame', params: params })
    },
    setRouterParams(params) {
      this.$set(params, 'itemName', this.routeData.itemName)
      this.$set(params, 'itemId', this.routeData.itemId)
      this.$set(params, 'currentPage', this.currentPage)
      this.$set(params, 'pageSize', this.pageSize)
      this.$set(params, 'itemCurrentPage', this.routeData.itemCurrentPage)
      this.$set(params, 'itemPageSize', this.routeData.itemPageSize)
    },
    addOrUpdate() {
      this.$refs['templateForm'].validate((valid) => {
        if (valid) {
          var params = {
            'name': this.templateForm.templateName,
            // 'code': this.templateForm.templateCode,
            // 'active': this.templateForm.active,
            'systemId': this.templateForm.systemId
          }
          var url = this.baseFormUrl + '/template/saveTemplate'
          if (this.updateTemplateId != 0) {//eslint-disable-line
            url = this.baseFormUrl + '/template/update'
            this.$set(params, 'id', this.updateTemplateId)
          }
          this.$axios.post(url,
            params
          ).then(res => {
            this.$message.success('操作成功~')
            this.dialogFormVisible = false
            this.templateName = ''
            // this.templateCode = ''
            this.updateTemplateId = 0
            this.getFormList()
          }).catch(() => {
            this.$message.error('操作失败！')
          })
        } else {
          this.$message.error('请正确输入')
          return false
        }
      })
    },
    copy(index, row) {
      var params = {
        'name': row.name + '-复制',
        'content': row.content,
        'systemId': row.systemId
      }
      var url = this.baseFormUrl + '/template/saveTemplate'
      this.$axios.post(url,
        params
      ).then(res => {
        this.$message.success('操作成功~')
        this.getFormList()
      }).catch(() => {
        this.$message.error('操作失败！')
      })
    },
    remove: function(index, row) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$axios.delete(this.baseFormUrl + '/template/remove', {
          params: {
            id: row.id
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getFormList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getFormList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getFormList()
    },
    // formatActive(row, column, cellValue, index) {
    //   if (row.active == 0) {//eslint-disable-line
    //     return '不可用'
    //   } else {
    //     return '可用'
    //   }
    // },
    add() {
      if (this.$refs['templateForm'] !== undefined) {
        this.$refs['templateForm'].resetFields()
      }
      // this.$set(this.templateForm, 'active', 0)
      // this.$set(this.templateForm, 'templateCode', '')
      this.$set(this.templateForm, 'templateName', '')
      this.$set(this.templateForm, 'systemId', '')
      this.updateTemplateId = 0
      this.dialogFormVisible = true
    },
    update(index, row) {
      if (this.$refs['templateForm'] !== undefined) {
        this.$refs['templateForm'].resetFields()
      }
      // this.$set(this.templateForm, 'active', row.active)
      // this.$set(this.templateForm, 'templateCode', row.code)
      this.$set(this.templateForm, 'templateName', row.name)
      this.$set(this.templateForm, 'systemId', row.systemId)
      this.updateTemplateId = row.id
      this.dialogFormVisible = true
    },
    back() {
      this.$router.push({ name: 'itemList',
        params: {
          'itemCurrentPage': this.routeData.itemCurrentPage,
          'itemPageSize': this.routeData.itemPageSize
        }
      })
    },
    bind(index, row) {
      var params = {
        'id': this.routeData.itemId,
        'templateId': row.id
      }
      this.$axios.post(this.baseItemUrl + '/item/update',
        params
      ).then(res => {
        this.$message.success(this.routeData.itemName + '与' + row.name + '绑定成功')
        this.routeData.templateId = row.id
        this.getFormList()
      }).catch(() => {
        this.$message.error('操作失败！')
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.id === this.routeData.templateId) {
        return 'success-row'
      }
      return ''
    },
    getSystemOptions() {
      this.$axios.get(this.basePortalUrl + '/system/findAll'
      ).then(res => {
        this.systemOptions = res.data.data
      }).catch(() => {
        this.$message.error('获取业务系统失败')
      })
    },
    versionHandleSizeChange(val) {
      this.versionPageSize = val
      this.versionCurrentPage = 1
      this.getVersionList(this.useId)
    },
    versionHandleCurrentChange(val) {
      this.versionCurrentPage = val
      this.getVersionList(this.useId)
    },
    getVersionList: function(id) {
      var params = {
        'pageSize': this.versionPageSize,
        'pageNum': this.versionCurrentPage,
        'name': '',
        'useId': id
      }
      this.$axios.get(this.baseFormUrl + '/template/useId/page', {
        params
      }).then(res => {
        this.versionData = res.data.data.records
        this.versionTotal = parseInt(res.data.data.total)
      }).catch(() => {
        this.$message.error('获取模板版本列表失败')
      })
    },
    version(index, row) {
      this.useId = row.id
      this.dialogVersionVisible = true
      this.getVersionList(row.id)
    },
    use(index, row) {
      const params = new FormData()
      params.append('oldId', this.useId)
      params.append('newId', row.id)
      this.$axios.post(this.baseFormUrl + '/template/changeVersion',
        params
      ).then((res) => {
        if (res.data.data) {
          this.$message.success('版本启用成功')
          this.dialogVersionVisible = false
          this.getFormList()
        } else {
          this.$message.error('版本启用失败')
        }
      }).catch(() => {
        this.$message.error('版本切换时系统出错')
      })
    }
  }
}
</script>
<style>
  .el-table .success-row {
    background: #f0f9eb;
  }
</style>

